﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class ResourceMgr : BaseManager<ResourceMgr>
{
    /// <summary>
    /// 同步加载资源的方法
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="name"></param>
    /// <returns></returns>
    public T Load<T>(string name) where T:Object
    {
        T res = Resources.Load<T>(name);
        if (res is GameObject)//如果是GameObject就实例化再返回出去
        {
            return GameObject.Instantiate(res);
        }
        else//其他类型的资源直接返回 
        {
            return res;
        }
    }
    /// <summary>
    /// 异步加载，提供给外部调用的方法
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="name"></param>
    /// <param name="callback">回调函数</param>
    public void LoadAsync<T>(string name, UnityAction<T> callback) where T : Object
    {
        MonoManager.GetInstance().StartCoroutine(ReallyLoadAsync(name,callback));
    }
    /// <summary>
    /// 真正异步加载的协程
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="name"></param>
    /// <returns></returns>
    private IEnumerator ReallyLoadAsync<T>(string name,UnityAction<T> callback) where T:Object
    {
        ResourceRequest res = Resources.LoadAsync<T>(name);
        yield return res;
        if (res.asset is GameObject)
        {
            callback(GameObject.Instantiate(res.asset) as T);
        }
        else
        {
            callback(res.asset as T);
        }
    }
}
